package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.constants.RedisConstants;
import com.hmdp.constants.SystemConstants;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import io.netty.util.internal.ResourcesUtil;
import io.netty.util.internal.StringUtil;
import io.netty.util.internal.SystemPropertyUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.hmdp.constants.RedisConstants.BLOG_LIKED_KEY;

/**
 * @author zdq
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IFollowService followService;

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{
            extracted(blog);
            blog.setIsLike(getIsMember(blog.getId()));
        });
        return Result.ok(records);
    }

    @Override
    public Result queryBlog(Long id) {
       // 根据id查询博客
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("博客不存在");
        }
        // 查询用户
        extracted(blog);
        // 博客是否被当前用户点赞
        blog.setIsLike(getIsMember(id));
        return Result.ok(blog);
    }

    @Override
    public Result likeBlog(Long id) {
        Long userId = UserHolder.getUser().getId();
        String key = BLOG_LIKED_KEY + id.toString();

        // 查看是否点赞过
        Boolean isMember = getIsMember(id);
        if (isMember) {
            // 已点赞
            boolean success = update().setSql("liked = liked - 1").eq("id", id).update();
            if (success) {
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }
        } else {
            // 未点赞
            boolean success = update().setSql("liked = liked + 1").eq("id", id).update();
            if (success) {
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
        }
        return Result.ok();
    }

    @Override
    public Result queryBlogLikes(Long id) {
        // redis中查找点赞用户top5
        String key = BLOG_LIKED_KEY + id.toString();
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (top5 == null || top5.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        String join = StrUtil.join(",", ids);
        List<User> userList = userService.query().in("id", ids).last("ORDER BY FIELD(id," + join + ")").list();
        List<UserDTO> userDTOS = userList.stream().map(item -> BeanUtil.copyProperties(item, UserDTO.class))
                .collect(Collectors.toList());

        return Result.ok(userDTOS);
    }

    @Override
    @Transactional
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean success = save(blog);
        if (!success) {
            return Result.fail("添加失败");
        }

        // 推送到关注的用户
        // 1.查询关注的用户号
        List<Follow> followList = followService.query().eq("follow_user_id", blog.getUserId()).list();

        // 2.保存探店博文id至用户的收件箱
        followList.forEach(item -> {
            String key = RedisConstants.FOLLOW_BLOG_KEY + item.getUserId();
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        });

        // 返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result getBlog(Long max, Long offset) {
        // 在redis中获取博文id
        Long userId = UserHolder.getUser().getId();
        String key = RedisConstants.FOLLOW_BLOG_KEY + userId;

        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0.0, max, offset, 2);

        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }
        long currentTime = 0L;
        int os = 1;
        ArrayList<Long> ids = new ArrayList<>();
        for (ZSetOperations.TypedTuple<String> item: typedTuples) {
            ids.add(Long.valueOf(Objects.requireNonNull(item.getValue())));
            long minTime = Objects.requireNonNull(item.getScore()).longValue();
            if (minTime == currentTime) {
                os += 1;
            } else {
                currentTime = minTime;
                os = 1;
            }
        }

        // 按顺序查询博文
        String join = StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id", ids)
                .last("order by field(id," + join + ")")
                .list();

        // 查询对应作者信息
        blogs.forEach(this::extracted);

        // 博客是否被当前用户点赞
        for (Blog blog: blogs) {
            blog.setIsLike(getIsMember(userId));
        }

        // 返回ScrollResult
        ScrollResult result = ScrollResult.builder()
                .offset(os)
                .minTime(currentTime)
                .list(blogs)
                .build();

        return Result.ok(result);
    }

    // 判断用户是否点过赞
    private Boolean getIsMember(Long id) {
        UserDTO user = UserHolder.getUser();
        // 未登录时直接返回 ‘未点赞’
        if (user == null) {
            return false;
        }

        Long userId = user.getId();
        String key = BLOG_LIKED_KEY + id.toString();
        return stringRedisTemplate.opsForZSet().score(key, userId.toString()) != null;
    }

    // 查询博客对应发布者的信息
    private void extracted(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
